package smoker.server;

import java.net.*;
import java.io.*;
import smoker.tools.*;

public class ConnectClientThread extends Thread {
	private boolean isRunning = true;
	private Socket client;
	private int clientId;
	private IServerCenter iServerCenter;
	
	public ConnectClientThread(IServerCenter iServerCenter, Socket client, int clientId) {
		this.iServerCenter = iServerCenter;
		this.client = client;
		this.clientId = clientId;
		this.start();
	}

	public void run() {
		InputStream is;
		try {
			is = client.getInputStream();
			while (isRunning) {
				if (is.available() > 0) {
					handleInputStream(is);
				}
				Thread.sleep(500);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void handleInputStream(InputStream is) {
		try {
			ObjectInputStream ois = new ObjectInputStream(is);
				Message message = (Message) ois.readObject();
				handleMessage(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void handleMessage(Message message) {
		int type = message.getType();
		switch (type) {
		case MsgType.TYPE_LOGIN:
			iServerCenter.sendLoginUser(this, message, clientId);
			break;
		case MsgType.TYPE_CHAT:
			ChatInfo chatMsg = (ChatInfo) message.getData();
			iServerCenter.chatWith(chatMsg);
			break;
		case MsgType.TYPE_OFFLINE:
			User offLineUser = (User) message.getData();
			iServerCenter.offLineInfromAboutAllClient(offLineUser);
			break;
		case MsgType.TYPE_UPDATE:
			User user = (User)message.getData();
			int ret = iServerCenter.updateUser(user);
			if( ret == 0) {
				sendMessage(new Message(MsgType.YTPE_UPDATEOK, null));
			}else {
				sendMessage(new Message(MsgType.YTPE_UPDATELOST, null));
			}
			break;
		}
	}

	public void sendMessage(Message message) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
			oos.writeObject(message);
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
